package cn.turboinfo.fuyang.api.domain.scheduler.usecase.order

import cn.turboinfo.fuyang.api.domain.common.service.custom.ServiceCustomService
import cn.turboinfo.fuyang.api.domain.common.service.order.RefundOrderService
import cn.turboinfo.fuyang.api.domain.common.service.wechat.WechatPayService
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase
import cn.turboinfo.fuyang.api.domain.util.DateTimeFormatHelper
import cn.turboinfo.fuyang.api.entity.common.enumeration.common.EntityObjectType
import cn.turboinfo.fuyang.api.entity.common.enumeration.common.FundsAccountType
import cn.turboinfo.fuyang.api.entity.common.enumeration.order.RefundChannelType
import cn.turboinfo.fuyang.api.entity.common.enumeration.order.RefundStatus
import cn.turboinfo.fuyang.api.entity.common.enumeration.order.RefundType
import cn.turboinfo.fuyang.api.entity.common.enumeration.order.ServiceOrderRefundStatus
import cn.turboinfo.fuyang.api.entity.common.pojo.custom.QServiceCustom
import cn.turboinfo.fuyang.api.entity.common.pojo.order.RefundOrderUpdater
import net.sunshow.toolkit.core.qbean.api.request.QPage
import net.sunshow.toolkit.core.qbean.api.request.QRequest
import net.sunshow.toolkit.core.qbean.helper.component.request.QPageRequestHelper
import org.springframework.stereotype.Component
import java.time.LocalDateTime

@Component
class SchedulerServiceCustomRefundStatusUseCase(
    private val serviceCustomService: ServiceCustomService,
    private val wechatPayService: WechatPayService,
    private val refundOrderService: RefundOrderService,
) : AbstractUseCase<SchedulerServiceCustomRefundStatusUseCase.InputData, SchedulerServiceCustomRefundStatusUseCase.OutputData>() {

    override fun doAction(input: InputData): OutputData {

        val request = QRequest.newInstance()
            .filterEqual(QServiceCustom.refundStatus, ServiceOrderRefundStatus.PROCESSING)

        var requestPage = QPage.newInstance()
            .paging(0, 100)

        QPageRequestHelper.request(request, requestPage, serviceCustomService::findAll)
            .onEach {
                // 查询退款订单
                refundOrderService.findByObjectId(EntityObjectType.SERVICE_CUSTOM, it.id)
                    ?.let { refundOrderList ->

                        var noRefundNum = 0
                        var successNum = 0
                        var failureNum = 0
                        var processingNum = 0

                        refundOrderList.onEach { refundOrder ->
                            if (refundOrder.refundType.equals(RefundType.WECHAT)) {

                                // 查询微信退款订单
                                wechatPayService.findByRefundId(refundOrder.id)
                                    ?.let { wechatPay ->

                                        val builder = RefundOrderUpdater
                                            .builder(refundOrder.id)
                                            .withWxTransactionId(wechatPay.transactionId)
                                            .withWxRefundId(wechatPay.refundId)
                                            .withUserReceivedAccount(wechatPay.userReceivedAccount)

                                        when (wechatPay.channel) {
                                            "ORIGINAL" -> builder.withRefundChannel(RefundChannelType.ORIGINAL)
                                            "BALANCE" -> builder.withRefundChannel(RefundChannelType.BALANCE)
                                            "OTHER_BALANCE" -> builder.withRefundChannel(RefundChannelType.OTHER_BALANCE)
                                            "OTHER_BANKCARD" -> builder.withRefundChannel(RefundChannelType.OTHER_BANKCARD)
                                        }

                                        when (wechatPay.fundsAccount) {
                                            "UNSETTLED" -> builder.withFundsAccount(FundsAccountType.UNSETTLED)
                                            "AVAILABLE" -> builder.withFundsAccount(FundsAccountType.AVAILABLE)
                                            "UNAVAILABLE" -> builder.withFundsAccount(FundsAccountType.UNAVAILABLE)
                                            "OPERATION" -> builder.withFundsAccount(FundsAccountType.OPERATION)
                                            "BASIC" -> builder.withFundsAccount(FundsAccountType.BASIC)
                                        }

                                        when (wechatPay.status) {
                                            "SUCCESS" -> {
                                                successNum++
                                                builder.withStatus(RefundStatus.SUCCESS)
                                                    .withSuccessTime(
                                                        LocalDateTime.parse(
                                                            wechatPay.successTime,
                                                            DateTimeFormatHelper.wechatDataTime
                                                        )
                                                    )
                                            }

                                            "CLOSED" -> builder.withStatus(RefundStatus.CLOSED)
                                            "PROCESSING" -> {
                                                processingNum++
                                                builder.withStatus(RefundStatus.PROCESSING)
                                            }

                                            "ABNORMAL" -> {
                                                failureNum++
                                                builder.withStatus(RefundStatus.ABNORMAL)
                                            }
                                        }

                                        refundOrderService.update(builder.build())

                                    }
                            } else if (refundOrder.refundType.equals(RefundType.NO_REFUND)) {
                                noRefundNum++
                            } else if (refundOrder.refundType.equals(RefundType.OFFLINE)) {
                                processingNum++
                            }
                        }

                        // 更新订单退款状态
                        if (processingNum > 0) {
                            serviceCustomService.refreshRefundStatus(it.id, ServiceOrderRefundStatus.PROCESSING)
                        } else if (successNum == 0 && failureNum == 0) {
                            serviceCustomService.refreshRefundStatus(it.id, ServiceOrderRefundStatus.NO_REFUND)
                        } else if (successNum > 0 && failureNum > 0) {
                            serviceCustomService.refreshRefundStatus(it.id, ServiceOrderRefundStatus.REFUND_PART)
                        } else {
                            if (successNum > 0 && failureNum == 0) {
                                serviceCustomService.refreshRefundStatus(it.id, ServiceOrderRefundStatus.SUCCESS)
                            } else if (successNum == 0 && failureNum > 0) {
                                serviceCustomService.refreshRefundStatus(it.id, ServiceOrderRefundStatus.FAILURE)
                            }
                        }

                    }
                    ?: logger.error { "未找到微信退款订单订单: ${it.id}" }
            }
        return OutputData()
    }

    class InputData : AbstractUseCase.InputData()

    class OutputData : AbstractUseCase.OutputData()

}
